package com.gooda.springboot.exp2.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

public class MyCommandLineRunner implements CommandLineRunner {

    Environment env;

    private static final Logger logger = LoggerFactory.getLogger(MyCommandLineRunner.class);

    public MyCommandLineRunner(Environment env) {
        this.env = env;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("CommandLineRunner睡眠10秒");
        Thread.sleep(1000);
        System.out.println("利用Spring Boot的自动装配的自定义CommandLineRunner");

        // random的RandomValuePropertySource产生一个32位的随机字符串
        System.out.println("生成一个随机字符串: ".concat(Objects.requireNonNull(env.getProperty("random."))));
    }


    /**
     * 自定义ApplicationReadyEvent的监听器
     */
    @Component
    static class MyApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

        @Override
        public void onApplicationEvent(ApplicationReadyEvent event) {
            System.out.println("自定义监听器监听到 ApplicationEvent");
            System.out.println(event.toString());
        }
    }

}
